/**
 * @file AreaTool.cpp
 *
 * @date 25/12/2011
 * @author Tales 
 *
 */

#include "AreaTool.hpp"
#include "../Graphics.hpp"
#include "Editor.hpp"
#include "../common/util.hpp"
#include "../model/Picture.hpp"
#include "../model/AreaCommand.hpp"

namespace yep
{

AreaTool::AreaTool(AreaCommandType type)
{
	this->type = type;
}

void AreaTool::start()
{
	drawing = false;
	Editor &editor = getEditor();
	SDL_FillRect(editor.getPreview(), NULL, 0x0);
}

void AreaTool::end()
{
}

void AreaTool::pressed(pair<int, int> pos, bool leftButton, bitset<5> state)
{
	if (leftButton && !drawing)
	{
		drawing = true;
		p1 = p2 = pos;
		Editor &editor = getEditor();
		Graphics g(editor.getPreview());
		g.setColor(editor.getColor());
		g.drawPixel(pos);
	}
}

void AreaTool::released(pair<int, int> pos, bool leftButton, bitset<5> state)
{
	if (drawing)
	{
		if (leftButton)
		{
			Editor &editor = getEditor();
			SDL_Rect changedArea = toSDL_Rect(p1, p2);
			SDL_FillRect(editor.getPreview(), &changedArea, 0x0);
			drawing = false;
			getPicture().addCommand(new AreaCommand(type, p1, pos, editor.getColor(), editor.getCurrentLayer()));
		}
	}
}

void AreaTool::moved(pair<int, int> pos, pair<int, int> offset, std::bitset<5> state)
{
	typedef void (Graphics::*AreaMethod)(const pair<int, int> &p1, const pair<int, int> &p2);
	static AreaMethod methods[] =
	{ &Graphics::drawRectangle, &Graphics::fillRectangle, &Graphics::drawEllipsis, &Graphics::fillEllipsis };
	if (drawing)
		if (state[BUTTON_LEFT])
		{
			Editor &editor = getEditor();
			SDL_Rect changedArea = toSDL_Rect(p1, p2);
			p2 = pos;
			SDL_FillRect(editor.getPreview(), &changedArea, 0x0);
			Graphics g(editor.getPreview());
			g.setColor(editor.getColor());
			(g.*methods[type])(p1, pos);
		}
}

} /* namespace yep */
